<template>
  <div ref="chartRef" style="height: 450px;"></div>
</template>

<script setup>
import {ref, onMounted, watch, nextTick} from 'vue'
import * as echarts from 'echarts'

const props = defineProps(['data'])
const chartRef = ref(null)
let chartInstance = null
defineExpose({
  changeTab
})
function changeTab() {
  nextTick(()=>{
    chartInstance.resize()
  })
}
onMounted(() => {
  chartInstance = echarts.init(chartRef.value)
  window.addEventListener('resize', () => chartInstance.resize())
})

watch(() => props.data, (newData) => {
  if (!chartInstance || !newData.length) return

  const option = {
    title: {
      text: '飞行高度变化',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const point = params[0].data
        return `时间: ${point.time.toFixed(3)}s<br>高度: ${point.position.hei.toFixed(1)}m`
      }
    },
    xAxis: {
      type: 'category',
      data: newData.map(d => d.time.toFixed(3)),
      name: '时间 (s)'
    },
    yAxis: {
      type: 'value',
      name: '高度 (m)',
      min: Math.min(...newData.map(d => d.position.hei)) - 100,
      max: Math.max(...newData.map(d => d.position.hei)) + 100
    },
    series: [{
      data: newData.map(d => ({
        value: d.position.hei,
        time: d.time,
        position: d.position
      })),
      type: 'line',
      smooth: true,
      areaStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(58, 95, 205, 0.7)'
          }, {
            offset: 1, color: 'rgba(58, 95, 205, 0.1)'
          }]
        }
      },
      lineStyle: {
        width: 3,
        color: '#3a5fcd'
      },
      symbol: 'emptyCircle',
      symbolSize: 6
    }]
  }

  chartInstance.setOption(option)
})
</script>